package com.pri.chat.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.net.ParseException;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.UserBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import com.pri.chat.R;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.dialog.CommunitySelector;
import com.pri.chat.model.JsonBean;
import com.pri.chat.model.UserInfoModel;
import com.pri.chat.model.UserModel;
import com.pri.chat.utils.Auth;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.PictureChoiceUtil;
import com.pri.chat.utils.StringUtils;
import com.pri.chat.utils.TimeUtils;
import com.pri.chat.view.ImageViewPlus;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.view.RxToast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/23
 */
public class MyInfoActivity extends BaseActivity {
    @BindView(R.id.iv_tou)
    ImageViewPlus ivTou;
    @BindView(R.id.et_login_name)
    EditText etLoginName;
    @BindView(R.id.iv_clean_phone)
    ImageView ivCleanPhone;
    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.et_birthday)
    TextView et_birthday;
    @BindView(R.id.et_xingzuo)
    TextView et_xingzuo;
    @BindView(R.id.et_tizhong)
    TextView et_tizhong;
    @BindView(R.id.et_tixing)
    TextView et_tixing;

    @BindView(R.id.et_city)
    TextView etCity;
    @BindView(R.id.et_nsr)
    TextView et_nsr;
    @BindView(R.id.et_sfgc)
    TextView et_sfgc;
    @BindView(R.id.et_jsyh)
    TextView et_jsyh;


    @BindView(R.id.et_sg)
    TextView et_sg;
    @BindView(R.id.et_xl)
    TextView etXl;
    @BindView(R.id.et_work)
    TextView etWork;
    @BindView(R.id.et_imotion)
    TextView etImotion;
    @BindView(R.id.et_option)
    EditText etOption;
    @BindView(R.id.tv_reg)
    TextView tvReg;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_info_layout;
    }

    @Override
    protected void initView() {
        setTitle("个人资料");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                if (!PictureSelector.obtainMultipleResult(data).isEmpty()) {
                    selectList = PictureSelector.obtainMultipleResult(data);
                    Glide.with(MyInfoActivity.this).load(selectList.get(0).getPath()).into(ivTou);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        Uri uri = Uri.parse(selectList.get(0).getPath());
                        File file = RxFileTool.getFilePhotoFromUri(this, uri);
                        uploadImg(file.getAbsolutePath());
                    } else {
                        uploadImg(selectList.get(0).getPath());
                    }

                }
                break;
        }
    }

    private UserBean userBean;

    @Override
    protected void initData() {
        initJsonData();
        SubscriberOnNextListener<BaseBean<UserBean>> onNextListener = baseBean -> {
            userBean = baseBean.getData();
            etLoginName.setText(userBean.getMemberInfo().getNcName());

            if (StringUtils.isEmpty(userBean.getMemberInfo().getHeadPic())) {
                ivTou.setImageResource(R.drawable.nim_avatar_default);
            } else {
                Glide.with(this).load(userBean.getMemberInfo().getHeadPic()).into(ivTou);
            }
            if (StringUtils.isEmpty(userBean.getMemberInfo().getCity())) {
                etCity.setText(SharedHelper.readValueByKeyForString(MyInfoActivity.this, "city"));
            } else {
                etCity.setText(userBean.getMemberInfo().getCity());
            }
            etImotion.setText(userBean.getMemberInfo().getQinggan());
            etOption.setText(userBean.getMemberInfo().getSignInfo());
            et_sg.setText(userBean.getMemberInfo().getShengao());
            etWork.setText(userBean.getMemberInfo().getZhiye());
            etXl.setText(userBean.getMemberInfo().getXueli());
            path = userBean.getMemberInfo().getHeadPic();
            tv_sex.setText(userBean.getMemberInfo().getSex());

            et_birthday.setText(userBean.getMemberInfo().getBirthDay());
            et_tizhong.setText(userBean.getMemberInfo().getTizhong());
            et_tixing.setText(userBean.getMemberInfo().getTixing());
            et_xingzuo.setText(userBean.getMemberInfo().getXingzuo());
            et_nsr.setText(userBean.getMemberInfo().getShouru());
            et_sfgc.setText(userBean.getMemberInfo().getSfgouche());
            et_jsyh.setText(userBean.getMemberInfo().getSfjsyuehui());

            initStartTimePicker();
        };
        UserModel userModel = new UserModel();
        userModel.setMemberId(SharedHelper.readId(this));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().getMemberCenterInfo(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    private UploadManager uploadManager = new UploadManager();
    private static final String TAG = "MyInfoActivity";

    private void uploadImg(String data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "img_" + sdf.format(new Date());
        String token = "ayjstx";
        uploadManager.put(data, key, Auth.create(HttpMethods.ACCESS_KEY, HttpMethods.SECRET_KEY).uploadToken(token),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            Log.i("qiniu", "Upload Success");
                            Log.d(TAG, "complete: " + HttpMethods.QN_PATH + key);
                            path = HttpMethods.QN_PATH + key;
                            setImgNim(HttpMethods.QN_PATH + key);
                        } else {
                            Log.i("qiniu", "Upload Fail");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, null);
    }

    private void setImgNim(String url) {
        Map<UserInfoFieldEnum, Object> fields = new HashMap<>(1);
        fields.put(UserInfoFieldEnum.AVATAR, url);
        NIMClient.getService(UserService.class).updateUserInfo(fields)
                .setCallback(new RequestCallbackWrapper<Void>() {
                    @Override
                    public void onResult(int code, Void aVoid, Throwable throwable) {
                        if (code == ResponseCode.RES_SUCCESS) {
                            LogUtil.i(TAG, "update userInfo success, update fields count=" + fields.size());
                        } else {
                            if (throwable != null) {
                                RxToast.normal("设置失败，请重试");
                                LogUtil.i(TAG, "update userInfo failed, exception=" + throwable.getMessage());
                            }
                        }

                    }
                });
    }

    private List<LocalMedia> selectList = new ArrayList<>();
    private String path = "";

    @OnClick({R.id.et_city, R.id.et_work, R.id.et_jsyh, R.id.et_sfgc, R.id.et_imotion, R.id.et_nsr, R.id.et_tixing, R.id.et_tizhong, R.id.iv_tou, R.id.tv_reg, R.id.et_xl, R.id.et_sg, R.id.et_birthday, R.id.et_xingzuo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_tou:
                PictureChoiceUtil.getInstance().choiceTouPic(this, selectList);
                break;
            case R.id.et_city:
                showPickerView();
                break;
            case R.id.tv_reg:
                httpModityInfo();
                break;
            case R.id.et_xl:
                showCommunityDialog(etXl);
                break;
            case R.id.et_sg:
                showShenGaoDialog(et_sg);
                break;
            case R.id.et_birthday:
                mStartDatePickerView.show();
                break;
            case R.id.et_xingzuo:
                showXingZuo(et_xingzuo);
                break;
            case R.id.et_work:
                showZhiYe(etWork);
                break;
            case R.id.et_tizhong:
                showTiZhong(et_tizhong);
                break;
            case R.id.et_tixing:
                showTiXing(et_tixing);
                break;
            case R.id.et_nsr:
                showNsr(et_nsr);
                break;
            case R.id.et_imotion:
                showQgzt(etImotion);
                break;
            case R.id.et_jsyh:
                showSfjsyhList(et_jsyh);
                break;
            case R.id.et_sfgc:
                showSfgcList(et_sfgc);
                break;

        }
    }

    private void httpModityInfo() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("修改资料成功");
            finish();

        };
        UserInfoModel userModel = new UserInfoModel();
        userModel.setId(SharedHelper.readId(this));
        userModel.setCity(getString(etCity));
        userModel.setQinggan(getString(etImotion));
        userModel.setShengao(getString(et_sg));
        userModel.setSignInfo(getString(etOption));
        userModel.setXueli(getString(etXl));
        userModel.setZhiye(getString(etWork));

        userModel.setBirthDay(getString(et_birthday));
        userModel.setTizhong(getString(et_tizhong));
        userModel.setTixing(getString(et_tixing));
        userModel.setXingzuo(getString(et_xingzuo));
        userModel.setShouru(getString(et_nsr));
        userModel.setSfgouche(getString(et_sfgc));
        userModel.setSfjsyuehui(getString(et_jsyh));
        userModel.setHeadPic(path);
        userModel.setNcName(getString(etLoginName));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().updateMember(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    TimePickerView mStartDatePickerView;

    /**
     * 初始化开始日期选择器控件
     */
    private void initStartTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = TimeUtils.strToCalendar(userBean.getMemberInfo().getBirthDay());
        //设置最小日期和最大日期
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();//最大日期是今天
        try {
            startDate.setTime(TimeUtils.strToDate("1970-01-01"));//设置为2006年4月28日
            endDate.setTime(TimeUtils.strToDate("2050-12-31"));//设置为2006年4月28日
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //时间选择器
        mStartDatePickerView = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                et_birthday.setText(TimeUtils.dataToStr(date, "yyyy-MM-dd"));
            }
        })
//                .setDecorView((RelativeLayout)findViewById(R.id.activity_rootview))//必须是RelativeLayout，不设置setDecorView的话，底部虚拟导航栏会显示在弹出的选择器区域
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTitleText("选择出生日期")//标题文字
                .setTitleSize(20)//标题文字大小
                .setTitleColor(getResources().getColor(R.color.color_333333))//标题文字颜色
                .setCancelText("取消")//取消按钮文字
                .setCancelColor(getResources().getColor(R.color.color_666666))//取消按钮文字颜色
                .setSubmitText("确定")//确认按钮文字
                .setSubmitColor(getResources().getColor(R.color.orange))//确定按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(R.color.orange))//设置选中文本的颜色值
                .setLineSpacingMultiplier(1.8f)//行间距
                .setDividerColor(getResources().getColor(R.color.gray))//设置分割线的颜色
                .setRangDate(startDate, endDate)//设置最小和最大日期
                .setDate(selectedDate)//设置选中的日期
                .build();
    }


    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private List<String> xlList = new ArrayList<String>() {
        {
            this.add("小学");
            this.add("初中");
            this.add("中专");
            this.add("高中");
            this.add("专科");
            this.add("本科");
            this.add("硕士");
            this.add("博士");
        }
    };

    private void showCommunityDialog(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, xlList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择学历");
        communitySelector.show();
    }


    private List<String> sgList = new ArrayList<String>() {
        {
            for (int i = 139; i < 199; i++)
                this.add(i + "cm");
        }
    };

    private void showShenGaoDialog(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, sgList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择身高(CM)");
        communitySelector.show();
    }

    private List<String> xzList = new ArrayList<String>() {
        {

            this.add("白羊座");
            this.add("金牛座");
            this.add("双子座");
            this.add("巨蟹座");
            this.add("狮子座");
            this.add("处女座");
            this.add("天蝎座");
            this.add("摩羯座");
            this.add("水瓶座");
            this.add("双鱼座");
        }
    };

    private void showXingZuo(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, xzList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择星座");
        communitySelector.show();
    }


    private List<String> zyList = new ArrayList<String>() {
        {
            this.add("销售");
            this.add("医生");
            this.add("行政");
            this.add("高管");
            this.add("教师");
            this.add("个体");
            this.add("媒体");
            this.add("金融");
            this.add("服务");
            this.add("IT");
            this.add("公务员");
            this.add("学生");
            this.add("农林");
            this.add("其他");
        }
    };

    private void showZhiYe(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, zyList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择职业");
        communitySelector.show();
    }

    private List<String> tzList = new ArrayList<String>() {
        {
            for (int i = 30; i < 121; i++)
                this.add(i + "kg");
        }
    };

    private void showTiZhong(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, tzList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择体重（KG）");
        communitySelector.show();
    }

    private List<String> txList = new ArrayList<String>() {
        {
            this.add("保密");
            this.add("匀称");
            this.add("纤瘦");
            this.add("苗条");
            this.add("丰满");
            this.add("胖");
            this.add("健壮");
            this.add("肌肉");
        }
    };

    private void showTiXing(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, txList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择体型");
        communitySelector.show();
    }

    private List<String> nsrList = new ArrayList<String>() {
        {
            this.add("10W以下");
            this.add("10W-20W");
            this.add("20W-30W");
            this.add("30W-60W");
            this.add("60W-100W");
            this.add("100W以上");
        }
    };

    private void showNsr(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, nsrList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {
                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择年收入");
        communitySelector.show();
    }

    private List<String> qgztList = new ArrayList<String>() {
        {
            this.add("单身");
            this.add("恋爱中");
            this.add("离异");
            this.add("已婚");
            this.add("保密");
        }
    };

    private void showQgzt(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, qgztList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择情感状态");
        communitySelector.show();
    }

    private List<String> sfgcList = new ArrayList<String>() {
        {
            this.add("是");
            this.add("否");
        }
    };

    private void showSfgcList(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, sfgcList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择是否购车");
        communitySelector.show();
    }

    private List<String> sfjsyhList = new ArrayList<String>() {
        {
            this.add("是");
            this.add("否");
        }
    };

    private void showSfjsyhList(TextView tv) {
        CommunitySelector communitySelector = new CommunitySelector(this, null, sfjsyhList, new CommunitySelector.CallBack() {
            @Override
            public void onConfirm(String checkInfo) {

                tv.setText(checkInfo);
            }
        });
        if (!StringUtil.isEmpty(tv.getText().toString())) {
            communitySelector.setCurrentView(tv.getText().toString());
        }
        communitySelector.setTitle("选择是否接受约会");
        communitySelector.show();
    }


    private ArrayList<JsonBean> options1Items = new ArrayList<>(); //省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private int opt1 = -1, opt2 = -1;

    private void showPickerView() {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                etCity.setText(options2Items.get(options1).get(options2));
                opt1 = options1;
                opt2 = options2;

            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(mContext.getResources().getColor(R.color.orange)) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items);//三级选择器
        if (opt1 != -1) {
            pvOptions.setSelectOptions(opt1, opt2);
        }
        pvOptions.show();
    }

    public String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private void initJsonData() {//解析数据 （省市区三级联动）
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         * */
        String JsonData = getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
